import sys
import os
import json
sys.path.append(os.getcwd())
from Sequence.system import SystemMain as system
from Sequence.mainCsv import MainCsvProcess as mainCSV
from Sequence.techCsv import TechCsvProcess as techCSV
from Sequence.limitCsv import LimitCsvProcess as limitCSV
from Sequence.limitCsv1 import LimitCsvProcess as limitCSV1
from Sequence.conditionCsv import ConditionCsvProcess as conditionCSV
from Sequence.import_function import Import_modules as import_function
import plistlib
from pathlib import Path

from UI.table import CustomTable as customTable

import time
import threading
from threading import Thread, current_thread

import UI.transfer as transfer

import random

from Log.outputLog import Log as log

work_path = Path(__file__).parent

# Group
Group = {}

# 存储变量的字典
VariableTable = {}

showGroupIndex = 0

# MainCSV的数组
MainCsvArray = []
# TechCSV的数组
TechCsvArray = []
# LimitCSV的数组
LmitCSVArray = []
# ConditionCSV的数组
ConditionCSVArray = []

TestMode = "Production"

params = None

def insertRecord(param,testDict,allData):
    

    upperLimit = 0
    value = 0
    lowerLimit = 0
    if testDict["upperLimit"] != "":
        upperLimit = int(testDict["upperLimit"])
    if testDict["value"]:
        print("---main---value :",testDict["value"])
        if testDict["value"] == False or testDict["value"] == True:
            value = testDict["value"]
        else:
            try:
                value = float(testDict["value"])
            except ValueError as e:
                value = testDict["value"]

    if testDict["lowerLimit"] != "":
        lowerLimit = float(testDict["lowerLimit"])
    
    passResult = "fail"
    # 上下限都有
    if testDict["upperLimit"] != "" and testDict["lowerLimit"] != "":
        print("上下限都有")
        if value >= lowerLimit and value <= upperLimit:
            passResult = "pass"

     # 只有上限
    if testDict["upperLimit"] != "" and testDict["lowerLimit"] == "":
        print("只有上限")
        if value < upperLimit:
            passResult = "pass"
    # 只有下限
    if testDict["upperLimit"] == "" and testDict["lowerLimit"] != "":
        print("只有下限")
        if value > lowerLimit:
            passResult = "pass"

    if testDict["upperLimit"] == "" and testDict["lowerLimit"] == "":
        passResult = "pass"
     
    #   增加结果是false或者true的判断
    if value == True:
        passResult = "pass"
    if value == False:
        passResult = "fail"
   

    tag = testDict["id"]
    gridValues = (
                    f"{tag}",
                    testDict["TestName"],
                    testDict["subTestName"],
                    testDict["subSubTestName"],
                    testDict["upperLimit"],
                    testDict["value"],
                    testDict["lowerLimit"],
                    passResult,
                    "no info",
                    "10"
    )

    recordColorTags = ""
    if passResult == "fail":
        recordColorTags = "red"
        param["tableTree"].insert('',tag,values=gridValues,tags=recordColorTags)

        print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
        param["resultArray"][int(param["groupIndex"])] = "1"
        print(param["resultArray"])
        print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")


    else:
        param["tableTree"].insert('',tag,values=gridValues,)
    
    param["tableTree"].tag_configure("red",background="#ff0000")
    param["tableTree"].update()
    # transfer.showDatas(self.dataGrid,item[index],self.resultArray,index)
    # def showDatas(treeview,datas,resultArray,index):
    
    # print(allData)

# 开始测试流程
def runTest(param,dataArrayShowInMian):
    print("start run test")

    dataKey = str(param["groupIndex"])
   
    functions = import_function()

    all_function = functions.all_modules

    # 获取Main.CSV全部数据
    MainCsvArray = mainCSV.getCsvContent()
    recordID = 0
    for mainV in MainCsvArray:
        # print(mainV["Technology"])
        Technology = mainV["Technology"]
        Tech_csv_path = os.path.join(Path(__file__).parent.parent,"Assets/Tech/"+Technology+".csv")
        
        if mainV["Disable"] != "Y":
            TechTestNameCsvDict = techCSV(Tech_csv_path).getCsvTechContent(mainV["TestName"])
            

            for techV in TechTestNameCsvDict[mainV["TestName"]]:
                if techV["Disable"].upper() == "Y":
                    continue
                
                if ":" in techV["TestActions"]:
                    TestActionsArray = techV["TestActions"].split(":")
                    TechName = TestActionsArray[0]
                    ActionName = TestActionsArray[1]
                    print("all_function[TechName].function_dic[ActionName](techV)",all_function[TechName].function_dic[ActionName],ActionName)
                    value = all_function[TechName].function_dic[ActionName](techV)
                    print("function return value00000:",value)
                    subsubTestName = ""
                    LimitDictResult = {}
                    if techV["AdditionalParameters"] != None and techV["AdditionalParameters"] != "":
                        AdditionalParameters = json.loads(techV["AdditionalParameters"])
                        subsubTestName = AdditionalParameters["paraName"]

                        LimitTestNameCsvDict = limitCSV1().getCsvLimitContent(mainV["TestName"],subsubTestName)
                        
                        if LimitTestNameCsvDict != {}:
              
                            LimitDictResult = LimitTestNameCsvDict
                    
                    recordID = recordID + 1

                    upperLimit = ""
                    lowerLimit = ""
                    if LimitDictResult != {}:
                        if LimitDictResult["upperLimit"] != "" and LimitDictResult["upperLimit"] != None:
                            
                            upperLimit = LimitDictResult["upperLimit"]

                    if LimitDictResult != {}:
                        if LimitDictResult["lowerLimit"] != "" and LimitDictResult["lowerLimit"] != None:
                            
                            lowerLimit = LimitDictResult["lowerLimit"]
                    
        
                    print("threading.currentThread().getName()",threading.currentThread().getName())
                    print("function return value:",value)
                    resultDict = {
                        "id":recordID,
                        "TestName":mainV["Technology"],
                        "subTestName":techV["TestName"],
                        "subSubTestName":subsubTestName,
                        "upperLimit":upperLimit,
                        "value":value,
                        "lowerLimit":lowerLimit,
                        "failureMessage":"no",
                    }
                    dataArrayShowInMian.append(resultDict)
                    
                    dataDictShowInMian = {
                        dataKey:dataArrayShowInMian
                    }

                    # 删除重复项
                    for index, item in enumerate(param["dataArray"]):
                        for key_name in item.keys():
                            if key_name == dataKey:
                                del param["dataArray"][index]
                                break

                    param["dataArray"].append(dataDictShowInMian)


                    for y in range(0,len(param["groupArray"])):
                        print("xxxxxxxxxxxx")
                        value_y = param["groupArray"][y]
                        if value_y == "1":
                            print(param["groupArray"][y])
                            if dataKey == str(y):
                                insertRecord(param,resultDict,param["dataArray"])
                                # time.sleep(1)

                    # insertRecord(param,resultDict,param["dataArray"])
    
    tearDownTest(param)

def tearDownTest(param):

     # 结束删除数据
    # del param["dataArray"][int(param["groupIndex"])]

    print("============result===========")
    print(param["resultArray"])

    transfer.checkRecord(param)


    TestResult = True
    if param["resultArray"][int(param["groupIndex"])] == "1":
        TestResult = False

    print("结束测试!!!!")
    param["enterEL"].ListenTestResultCallback(int(param["groupIndex"]),TestResult)
    # ListenTestResultCallback
                    
    
# 程序入口
def main_(param,dataArrayShowInMian):
    print("start main")

    print(threading.current_thread())

    # # print(UI.gol.get_value("name"))
    # print(type(param["dataArray"]))

    # print(param["dataArray"])
    print(param)
    # print("url--------",param["urls"])
    # 开始跑测试序列
    runTest(param,dataArrayShowInMian)
    
def main(*args,**kargs):
    log().LogInfo("device start test")
    params = args[0]

    print("args:{}kargs{}".format(args,kargs))
    # print(kargs)
    print(params["groupIndex"])
    global showGroupIndex 
    showGroupIndex = params["groupIndex"]
    print("===========")
    print(showGroupIndex)
    # print("tableTree type------:",type(params["tableTree"]))

    dataKey = "Group"+ str(params["groupIndex"])

    dataArrayShowInMian = []

    dataArrayShowInMian.clear()

    global TestMode 
    if TestMode == "Production":
        print("Start Production")
        
        TestMode = "Production"
    else:
        
        print("Start Audit")
        
        TestMode = "Audit"

    main_(params,dataArrayShowInMian)

    pass





    